package spider.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
/**
 * @说明：
 * @author: gaoll
 * @CreateTime:2014-11-13
 * @ModifyTime:2014-11-13
 */
public class HttpGetConnect {
	
	/**
	 *  
	 * @param url
	 * @param charsetName  UTF-8、GB2312
	 * @return
	 * @throws IOException
	 */
	public String connect(String url,String charsetName) throws IOException{
		BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
		
		CloseableHttpClient httpclient = HttpClients.custom()
	            .setConnectionManager(connManager)
	            .build();
		String content = "";
		
		try{
			HttpGet httpget = new HttpGet(url);
			
			RequestConfig requestConfig = RequestConfig.custom()
	                .setSocketTimeout(5000)
	                .setConnectTimeout(5000)
	                .setConnectionRequestTimeout(5000)
	                .build();
	        httpget.setConfig(requestConfig);
			httpget.addHeader( "User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 " +
					"(KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");  
			httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");  
		    httpget.setHeader("Accept-Charset", "GB2312,utf-8;");  
		    
			CloseableHttpResponse response = httpclient.execute(httpget);
			
			int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
            	
                HttpEntity entity = response.getEntity();
                InputStream instream = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(instream,charsetName));
				StringBuffer sbf = new StringBuffer();
				String line = null;
				while ((line = br.readLine()) != null){
					sbf.append(line);
				}

				br.close();
				content = sbf.toString();
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			httpclient.close();
		}
		//log.info("content is " + content);
		return content;
	}
	
	private static Log log = LogFactory.getLog(HttpGetConnect.class);
}
